<template>
	<view class="content poRel">
		<swiper style="box-sizing: border-box;background-size: 100% 100%;" class="wid100 dis disAl tu1" circular
			:autoplay='true' indicator-active-color="#3E86FF">
			<swiper-item v-for="(item,index) in banner" :key="index">
				<image :src="ossurl+item.image" class="wh100"></image>
			</swiper-item>
		</swiper>
		<view class="mar-top40 wid90 mar foSi40 fowe600" style="color: #C38D5F;">放生鱼品种</view>
		<view class="wid90 mar dis flwa mar-top40">
			<block v-for="(item,index) in list" :key="index">
				<view class="textCen wid33" @click="xuanze(index)">
					<image :src="ossurl+item.image" :class="goods_id != item.id?'weixuan':''" class="img"></image>
					<view class="mar-top10 textCen" style="color: #C38D5F;">
						<view class="foSi35">{{item.name}}</view>
						<view class="foSi25">{{item.money}}元/条</view>
						<view class="foSi25">（{{item.unit}}）</view>
					</view>
				</view>
			</block>
		</view>
		<view class="mar-top40 wid90 mar foSi50 fowe600" style="color: #C38D5F;">放生留言</view>
		<view class="mar-top40 wid85 mar tax bacFFF">
			<textarea class="wh100" style="line-height: 46rpx;" v-model="taxt" />
		</view>
		<view style="height: 110rpx;"></view>
		<view class="wid100 poFix" style="bottom: 0;background-color: #F6F3EE;">
			<view class="wid90 mar hei80 dis disAl disJuB">
				<view class="fowe600 moy">¥{{money}}</view>
				<!-- #ifdef H5 -->
						<wx-open-subscribe :template="templateIds[0]" class="dis disAl disJuC borRad40 hei100 coFFF foSi35 zhifu wid100" style="color:#fff" id="subscribe-btn" ref="subscribeBtn">
					<script type="text/wxtag-template">
						<div style="width:100%;height:100%;color:#fff;text-align:center;">立即支付</div>
					</script>
				</wx-open-subscribe>
				<!-- #endif -->

				<!-- #ifdef MP-WEIXIN -->
				<view class="dis disAl disJuC borRad40 hei100 coFFF foSi35 zhifu" @click="dingyue()">立即支付</view>
				<!-- #endif -->

			</view>
			<view style="height: 30rpx;"></view>
		</view>
	</view>
</template>

<script>
	// #ifdef H5
	var jweixin = require('jweixin-module');
	// #endif
	export default {
		data() {
			return {
				url: this.global.url,
				ossurl: this.global.ossurl,
				taxt: '',
				banner: [],
				list: [],
				money: 0,
				goods_id: 0,
				templateIds: ['-pBjraS7Fitkfp7zBmfXylslUw7N42wAwLdRr7vpQ4U']
			}
		},
		onLoad() {
			this.indexList()
			this.getGoods()
			this.alioss()
		},
		onReady() {
			// #ifdef H5
				this.getInfo()
			// #endif
		},
		methods: {
			alioss(){
				var that  = this;
				uni.request({
				    // http://jufeng.tengshuokeji.cn//yonghu/order/order_comments
				    url: that.global.url + '/api/index/alioss',
				    method: "POST",
				    data: {},
				    success(res) {
				        let result = res.data
				        console.log(result)
				        if (result.code == 1) {
				            that.global.ossurl = result.data
							console.log(that.global.ossurl);
							that.ossurl = that.global.ossurl;
				        }
				    }
				})
			},
			xuanze(index) {
				this.money = this.list[index].money
				this.goods_id = this.list[index].id
			},
			indexList() {
				var that = this
				uni.request({
					url: that.global.url + '/api/index/banneranimals',
					data: {},
					header: {
						'Content-Type': 'application/json' //自定义请求头信息
					},
					method: 'POST', //请求方式，必须为大写
					success: (res) => {
						that.banner = res.data.data.banner
					}
				})
			},
			getGoods() {
				var that = this
				uni.request({
					url: that.global.url + '/api/goods',
					data: {
						type: 2,
						page: 1,
						size: 10
					},
					header: {
						'Content-Type': 'application/json' //自定义请求头信息
					},
					method: 'POST', //请求方式，必须为大写
					success: (res) => {
						that.list = res.data.data.list
						if (res.data.data.list.length > 0) {
							that.money = that.list[0].money
							that.goods_id = that.list[0].id
						}

					}
				})
			},
			getInfo() {
			  var that = this;
			  uni.request({
				url: that.global.url + '/api/user/getJsConfig',
				method: 'POST',
				header: {
					"token": uni.getStorageSync('token')
				},
				data: {
					url:encodeURIComponent(location.href.split('#')[0])
				},
				success: (res) => {
				  console.log(res.data.data);
				  let w_pay = res.data.data
				  console.log(w_pay);
				  jweixin.config({
					debug: false,
					appId: w_pay.appId,
					timestamp: w_pay.timestamp,
					nonceStr: w_pay.nonceStr,
					signature: w_pay.signature,
					jsApiList: ['wx-open-subscribe'],
					openTagList: ['wx-open-subscribe']
				  })
				  // config 准备好了那么就开始操作了，
				  jweixin.ready(() => {
				  // wx-open-subscribe 原生绑定点击事件
					this.$nextTick(() => {
						const btn = this.$refs.subscribeBtn;
						btn.addEventListener('success', ({
							detail
						}) => {
							this.content2 = JSON.parse(detail.subscribeDetails)
							for (var i in this.content2) {
							  if (i === this.templateIds[0] || i ===
								'-pBjraS7Fitkfp7zBmfXylslUw7N42wAwLdRr7vpQ4U') {
								let status = JSON.parse(this.content2[i]).status
								console.log(status)
								console.log(this.content2)
								if (status === 'accept') {
									that.zhifu()
								} else if (status === 'reject') {
									that.zhifu()
								}
							  }
							}
						});
						btn.addEventListener('error', (e) => {
							alert('授权失败了，请重试')
						});
					})
				  })
				}
			  })
			},
			dingyue() {
				var that = this
				// 要检查的订阅id
				let id = 'ehNoirrdGXfQwaAGKyzb_JiH_ipins4ld0P4XTonB-c'
				// 这里是获取下发权限地方，根据官方文档，可以根据  wx.getSetting() 的 withSubscriptions   这个参数获取用户是否打开订阅消息总开关。后面我们需要获取用户是否同意总是同意消息推送。所以这里要给它设置为true 。
				wx.getSetting({
					withSubscriptions: true, //  这里设置为true,下面才会返回mainSwitch
					success: function(res) {
						// 调起授权界面弹窗
						if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关
							if (res.subscriptionsSetting.itemSettings !=
								null) { // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
								that.zhifu()
							} else {
								// 当用户没有点击 ’总是保持以上选择，不再询问‘  按钮。那每次执到这都会拉起授权弹窗
								wx.showModal({
									title: '提示',
									content: '请授权开通服务通知',
									showCancel: true,
									success: function(ress) {
										if (ress.confirm) {
											wx.requestSubscribeMessage({ // 调起消息订阅界面
												tmplIds: [id],
												success(res) {
													console.log('订阅消息 成功 ');
													console.log(res);
													that.zhifu()
												},
												fail(er) {
													console.log("订阅消息 失败 ");
													console.log(er);
													that.zhifu()
												}
											})
										}
									}
								})
							}
						} else {
							console.log('订阅消息未开启')
							that.zhifu()
						}
					},
					fail: function(error) {
						console.log(error);
						that.zhifu()
					},
				})
			},
			zhifu() {
				let that = this
				if (that.taxt == '') {
					uni.showToast({
						title: '请输入放生留言',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				uni.showLoading({
					title: '支付中...'
				})
				// #ifdef H5
				var method = 'mp'
				// #endif
				// #ifdef MP-WEIXIN
				var method = 'miniapp'
				// #endif
				uni.request({
					url: that.global.url + '/api/order/order_pay',
					method: 'POST',
					header: {
						"token": uni.getStorageSync('token')
					},
					data: {
						method: method,
						goods_id: that.goods_id,
						type: 2,
						note: that.taxt,
						openid: uni.getStorageSync('openid')
					},
					success: (res) => {
						let result = res.data
						if (result.code == 1) {
							console.log(result.data)
							if (method == 'mp') {
								jweixin.config({
									debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
									appId: result.data.appId, // 必填，公众号的唯一标识
									timestamp: result.data.timeStamp, // 必填，生成签名的时间戳
									nonceStr: result.data.nonceStr, // 必填，生成签名的随机串
									signature: result.data.paySign, // 必填，签名
									jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
								})
								jweixin.ready(function() {
									jweixin.chooseWXPay({
										appId: result.data.appId,
										package: result.data.package, //
										timestamp: result.data.timeStamp, // 时间戳
										nonceStr: result.data.nonceStr, // 随机数
										signType: result.data.signType,
										paySign: result.data.paySign, // 签名
										success: function() {
											// 支付成功
											uni.showModal({
												title: '提示',
												content: '支付成功',
												showCancel: false,
												success: function(res) {
													if (res.confirm) {
														uni.navigateTo({
															url: '/pages/orderForm/animalsForm',
														});
													}
												}
											})
										},
										cancel: function() {
											// 支付失败
											console.log(res)
											uni.showToast({
												title: '取消支付',
												icon: 'none',
												duration: 2000
											})
										},
										fail: function() {
											// 支付失败
											console.log(res)
											uni.showToast({
												title: '支付失败',
												icon: 'none',
												duration: 2000
											})
										}
									})
								})
							} else {
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: result.data.timeStamp,
									nonceStr: result.data.nonceStr,
									package: result.data.package,
									signType: 'MD5',
									paySign: result.data.paySign,
									success: function(res) {
										console.log(res);
										uni.showModal({
											title: '提示',
											content: '支付成功',
											showCancel: false,
											success: function(res) {
												if (res.confirm) {
													uni.navigateTo({
														url: '/pages/orderForm/animalsForm',
													});
												}
											}
										})
									},
									fail: function(err) {
										console.log('fail:' + JSON.stringify(err));
										// 支付失败
										console.log(err)
										uni.showToast({
											title: '支付失败',
											icon: 'none',
											duration: 2000
										})
									}
								});
							}
						} else if (result.code == 401) {
							uni.reLaunch({
								url: '/pages/login/login',
							})
						} else {
							uni.showToast({
								title: result.msg,
								icon: 'none',
								duration: 2000
							})
						}
					},
					complete() {
						uni.hideLoading()
					}
				});
			}
		}
	}
</script>

<style>
	.content {
		height: 100vh;
		background-color: #F6F3EE;
	}

	.tu1 {
		height: 450rpx;
	}

	.img {
		width: 180rpx;
		height: 180rpx;
	}

	.tax {
		height: 190rpx;
		padding: 21rpx 2.5%;
	}

	.moy {
		font-size: 60rpx;
		color: #F88607;
		line-height: 41rpx;
		letter-spacing: 1px;
	}

	.zhifu {
		width: 261rpx;
		background-color: #F88607;
	}

	.weixuan {
		background: #f6f3ee;
		opacity: 0.5;
	}
</style>